const express = require('express');
const r = express.Router();
const pool = require('../util/pool.js');


//URL:http://127.0.0.1:8080/v1/laptops/list
r.get('/list', (req, res, next) => {
    pool.query('select * from xz_laptop', (err, results) => {
        if (err) {
            next(err);
            return;
        }
        // console.log(results);
        res.send(results);
        // res.send({ code: 200, msg: "查询成功！" });
    });
});

// URL：http://127.0.0.1:8080/v1/laptops/upload
r.post('/upload', (req, res, next) => {
    let obj = req.body;
    // console.log(obj);
    let x, sta = 400;
    for (x in obj) {
        if (!obj[x]) {//x属性名， obj[x]属性值
            res.send({ code: sta, msg: x + '不能为空' });
            //阻止往后执行
            return;
        }
        sta++;
    }
    pool.query('insert into xz_laptop set ?', [obj], (err, rusults) => {
        console.log('rusults: ', rusults);
        if (err) {
            next(err);
            return;
        }

        res.send({ code: 200, msg: '上传成功' });
    });
});

// URL：http://127.0.0.1:8080/v1/laptops/update
r.put('/update', (req, res, next) => {
    let obj=req.body;
    // console.log(obj)
    let x,sta=400;
    for(x in obj){
        if(!obj[x]){
            res.send({ code: sta, msg: x + '不能为空' });
            return;
        }
    }
    pool.query('update xz_laptop set ? where lid=?',[obj,obj.lid],(err,results)=>{
        // console.log(results);
        if(err){
            next(err);
            return;
        }
        if(results.changedRows==0){
            res.send({code:201,msg:'修改失败！'});
            return;
        }
        res.send({ code: 200, msg: '更新成功！' });
    });

    // res.send({ code: 200, msg: '更新成功！' });
});


// URL：http://127.0.0.1:8080/v1/laptops/delete 1
r.delete('/delete:lid', (req, res, next) => {
    let lid = req.params.lid;
      pool.query('delete from xz_laptop where lid=?',[lid],(err,results)=>{
          if(err){
              next(err);
              return;
          }
          if (results.affectedRows === 0) {
            res.send({ code: 404, msg: '删除失败' });
        } else {
            res.send({ code: 200, msg: '删除成功' });
        }
      });
    // res.send({code:200,msg:'删除成功！'});
});
module.exports = r;